<template>
    <el-row>
        <el-col class="btn">
            <el-dialog :visible.sync="dialogVisible" width="625px" :before-close="handleClose" @close="handleClose()">
                <div slot="title" class="dialog-title box box-align-center">
                    <i class="title-icon"></i>
                    <span class="title-text ml10">{{ title }}</span>
                </div>
                <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="reset-form">
                    <el-form-item label="学校名称" prop="name">
                        <el-input v-model="form.name" class="text"></el-input>
                    </el-form-item>
                    <el-form-item label="学校logo">
                        <el-upload class="avatar-uploader" :action="uploadfileurl" :show-file-list="false"
                            :on-progress="progress" :on-success="success" :before-upload="beforeUpload">
                            <img v-if="form.logo" :src="form.logo" class="avatar">
                            <div v-else class="upload-icon">
                                <i class="el-icon-upload"></i>
                                <span class="schoollogo">46*46</span>
                            </div>
                            <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                        </el-upload>
                        <el-progress v-if="showProgress" :percentage="progInt"></el-progress>
                    </el-form-item>
                    <el-form-item label="学校位置">
                        <el-input class="text" v-model="form.address"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话">
                        <el-input class="text" v-model="form.tel"></el-input>
                    </el-form-item>
                    <el-form-item label="服务期限" v-show="role == 'super'">
                        <el-select v-model="form.serverTime" placeholder="请选择" @change="xzrq" class="text">
                            <el-option label="7天" value="7"></el-option>
                            <el-option label="1年" value="365"></el-option>
                            <el-option label="2年" value="730"></el-option>
                            <el-option label="3年" value="1095"></el-option>
                        </el-select>
                        <span>截止时间：{{ endTime }}</span>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button class="reset-cancel-btn" @click="handleClose()">取 消</el-button>
                    <el-button class="reset-comfirm-btn" @click="onSubmit('form')" v-loading.fullscreen.lock="fullscreenLoading">保 存</el-button>
                </span>
            </el-dialog>
        </el-col>
    </el-row>
</template>

<script>
    import {
        debounce
    } from 'lodash';
    export default {
        props: {
            dialogVisible: {
                default: false
            },
            title: {
                default: '提示'
            },
            info: {

            },
            id: {},
        },
        data() {
            var checkSchool = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入学校名称'));
                }else{
                    let params = {
                        searchText:value
                    };
                    this.$ajax.post('/yschool/pagelist', params).then(res => {
                        if (res.code == '0') {
                            console.log(res.page.list.map(r=>{return r.id}).filter(o=>o == this.form.id).indexOf(this.form.id) !=-1);
                            let isTrue = res.page.list.map(r=>{return r.id}).filter(o=>o == this.form.id).indexOf(this.form.id) !=-1
                            if(res.page.list.length>0){
                                if(!isTrue){
                                    return callback(new Error('学校名称存在'));
                                }
                                else{
                                    return callback();
                                }
                            }else{
                                 return callback();
                            }
                        }
                    })
                }
            };
            return {
                fullscreenLoading: false,
                endTime: '0000-00-00',
                loginInfo: this.$store.state.loginInfo,
                uploadfileurl: this.$url.baseURL + '/upload/uploadfile',
                showProgress: false,
                progInt: 0,
                form: {
                    id: '',
                    name: '',
                    logo: '',
                    address: '',
                    tel: '',
                    serverTime: ''
                },
                rules: {
                    name: [{
                        validator: checkSchool,
                        trigger: ['blur']
                    }],
                },
                schoolid: this.$store.state.schoolId,
                role: this.$store.state.maxRole,
                pageList: []
            };
        },
        mounted() {
            this.$bus.$on('pageList', (params) => {
                this.pageList = params
            })
        },
        methods: {
            getById() {

            },
            updateInfo() {
                this.$nextTick(() => {
                    if (this.title == '修改学校') {
                        this.endTime = this.info.endTime,
                            this.form.id = this.info.id,
                            this.form.name = this.info.name,
                            this.form.logo = this.info.logo,
                            this.form.address = this.info.address,
                            this.form.tel = this.info.tel
                    } else {
                        this.endTime = '0000-00-00',
                            this.form = {
                                id: '',
                                name: '',
                                logo: '',
                                address: '',
                                tel: '',
                                serverTime: ''
                            }
                    }
                })

            },
            handleClose() {
                this.$emit('clickClose')
            },
            onSubmit(formName) {
                // alert(111)
                let pid = 0;
                if (this.role == 'team') { //服务团队  默认一年
                    this.xzrq(365);
                    pid = this.loginInfo.user.schoolId;
                }
                // var params = {
                //     'id': this.form.id,
                //     'name': this.form.name,
                //     'logo': this.form.logo,
                //     'address': this.form.address,
                //     'tel': this.form.tel,
                //     'serverDate': this.endTime,
                //     'createUser': this.loginInfo.user.userCode,
                //     'pid':pid
                // };
                let url;
                let params;
                if (this.role == 'super') {
                    url = '/yschool/superAdd';
                    params = {
                        'id': this.form.id,
                        'name': this.form.name,
                        'logo': this.form.logo,
                        'address': this.form.address,
                        'tel': this.form.tel,
                        'serverDate': this.endTime,
                        'createUser': this.loginInfo.user.userCode,
                        'pid': pid
                    }
                } else if (this.role == 'team') {
                    url = '/yschool/add';
                    params = {
                        createuserid: this.loginInfo.user.id,
                        'id': this.form.id,
                        'name': this.form.name,
                        'logo': this.form.logo,
                        'address': this.form.address,
                        'tel': this.form.tel,
                        'serverDate': this.endTime,
                        'createUser': this.loginInfo.user.userCode,
                        'pid': pid
                    }
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.fullscreenLoading = true;
                        this.$ajax.post(url, params).then(res => {
                             this.fullscreenLoading = false;
                            if (res.code == '0') {
                                this.handleClose()
                                this.$message.success('操作成功！');
                                this.$emit('updateList')
                            } else {
                                this.$message.error('操作失败！');
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });

                // this.$api.sxxgl.tjxx(params).then(res => {
                //     if (res.code == '0') {
                //         this.handleClose()
                //         this.$message.success('操作成功！');
                //         this.$emit('updateList')
                //     } else {
                //         this.$message.error('操作失败！');
                //     }
                // })
            },
            xzrq(e) {
                var date = new Date();
                var ms = e * (1000 * 60 * 60 * 24)
                var newdate = new Date(date.getTime() + ms);
                this.endTime = this.formatDate(newdate);
            },
            formatDate(date) {
                if (!date) return '- -';
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                month = month < 10 ? '0' + month : month;
                var day = date.getDate();
                day = day < 10 ? '0' + day : day;
                var h = date.getHours();
                h = h < 10 ? '0' + h : h;
                var m = date.getMinutes();
                m = m < 10 ? '0' + m : m;
                return year + '-' + month + '-' + day;
            },
            progress(event) {
                this.showProgress = true;
                this.progInt = parseInt(event.loaded / event.total * 100, 10);
            },
            success(response, file, fileList) {
                this.showProgress = false;
                this.form.logo = response.body.data.url;
            },
            beforeUpload(file) {
                const fileName = file.name;
                const index = fileName.lastIndexOf(".");
                const ext = fileName.substr(index + 1);
                const arr = ["jpg", "png", "gif", "jpeg"];
                const isOk = arr.includes(ext);
                if (!isOk) {
                    this.$message.warning('logo格式暂不支持！');
                    return false;
                }
                var imgSize = file.size / (1024 * 1024);
                if (imgSize > 50) {
                    this.$message.warning(`当前文件${parseInt(imgSize)}M,上传文件不能超过50M`)
                    return false
                }
            },
        }
    };
</script>

<style scoped lang="scss">
    .upload-icon {
        width: 110px;
        height: 110px;
        line-height: 110px;
        color: #626BF1;
        font-size: 30px;
        border-radius: 10px;
        border: .1px solid #E4E7ED;
    }

    .avatar {
        width: 110px;
        height: 110px;
    }

    .schoollogo {
        font-size: 12px;
        position: absolute;
        left: 40px;
        top: 30px;
    }
</style>
